﻿using System;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using EOSCRM.Dao;
using EOSCRM.Domain;
using EOSCRM.Util;
using EOSCRM.Web.Common;
using EOSCRM.Web.Shared;

namespace EOSCRM.Web.Forms.HeThong
{
    public partial class NguoiDung : Authentication
    {
        private readonly UserAdminDao _objDao = new UserAdminDao();
        private readonly GroupDao _groupdao = new GroupDao();
        private readonly NhanVienDao _nvdao = new NhanVienDao();

        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }

            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }

        public UserAdmin UserAdmin
        {
            get
            {
                if (IsDataValid() == false)
                    return null;

                var objInfo = new UserAdmin();

                if(!string.IsNullOrEmpty(hdId.Value) && CheckUtil.IsInteger(hdId.Value))
                {
                    objInfo = _objDao.Get(null, Int32.Parse(hdId.Value));
                    objInfo.UpdateBy = LoginInfo.Username;
                    objInfo.UpdateDate = DateTime.Now;
                }
                else
                {
                    objInfo.CreateBy = LoginInfo.Username;
                    objInfo.UpdateBy = LoginInfo.Username;
                    objInfo.CreateDate = DateTime.Now;
                    objInfo.UpdateDate = DateTime.Now;
                    objInfo.Username = txtUSERNAME.Text.Trim();
                    // CommonFunc.MD5("");
                    objInfo.Active = true;
                    objInfo.MaNV = txtMaNv.Text.Trim();
                }

                return objInfo;
            }
        }

        protected int? UserId
        {
            get { return int.Parse(Session["NGUOIDUNG_USERID"].ToString()); }
            set { Session["NGUOIDUNG_USERID"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    // Bind data for grid view
                    LoadStaticReferences();
                    BindDataForGrid();
                    ClearForm();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private bool IsDataValid()
        {
           

            var nv = _nvdao.Get(txtMaNv.Text.Trim());
            if (nv == null)
            {
                ShowError("Mã nhân viên không hợp lệ.", txtMaNv.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtMaNv.Text.Trim()))
            {
                ShowError("Chưa chọn Nhân Viên", txtMaNv.ClientID);
                return false;
            }

            if (string.Empty.Equals(txtUSERNAME.Text.Trim()))
            {
                ShowError("Tên đăng nhập không hợp lệ.", txtUSERNAME.ClientID);
                return false;
            }
/*
            if (string.Empty.Equals(txtPASSWORD.Text.Trim()))
            {
                ShowError("Mật khẩu không hợp lệ.", txtPASSWORD.ClientID);
                return false;
            }

            
            var nhom = _groupdao.Get(int.Parse(ddlNHOM.SelectedValue));
            if(nhom == null)
            {
                ShowError("Vui lòng chọn nhóm.", ddlNHOM.ClientID);
                return false;
            }*/

            return true;
        }
        
        private void BindDataForGrid()
        {
            try
            {
                var objList = _objDao.GetList();
                gvNguoiDung.DataSource = objList;
                gvNguoiDung.PagerInforText = objList.Count.ToString();
                gvNguoiDung.DataBind();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void LoadGroupDataList()
        {
            var list = _groupdao.GetList(null);
            dpDataList.DataSource = list;
            dpDataList.DataBind();
        }

        private void LoadStaticReferences()
        {
            UserId = null;
        }
        
        private void ClearForm()
        {
            txtUSERNAME.Text = "";
            txtMaNv.Text = "";
            //txtPASSWORD.Text = "";
            //ddlNHOM.SelectedIndex = 0;
            //cbActive.Checked = true;
            UpdateMode = Mode.Create;
        }

        private void UpdateUserGroup()
        {
            var usrgrplist = new List<GroupUser>();
            for (var i = 0; i < dpDataList.Items.Count; i++)
            {
                var cb = dpDataList.Items[i].FindControl("chkGroupUser") as HtmlInputCheckBox;
                if (cb == null || !cb.Checked) continue;

                var groupId = cb.Attributes["title"].Trim();

                usrgrplist.Add(new GroupUser { GroupId = int.Parse(groupId), UserId = UserId.Value});
            }

            _objDao.UpdateUserGroupList(usrgrplist, UserId.Value);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var userObj = UserAdmin;
            if (userObj == null)
            {
                CloseWaitingDialog();
                return;
            }
            Message msg;
            if (UpdateMode == Mode.Create)
            {
                var tontai = _objDao.Get(txtUSERNAME.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Tên đăng nhập đã tồn tại", txtUSERNAME.ClientID);
                    return;
                }
                userObj.Password = "123456";
                msg = _objDao.Insert(userObj);
            }
            else
            {
                var tontai = _objDao.Get(txtUSERNAME.Text.Trim(),txtMaNv.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Tên đăng nhập đã tồn tại", txtUSERNAME.ClientID);
                    return;
                }
                msg = _objDao.Update(userObj);
            }
            
            UserId = userObj.Id;
            
            CloseWaitingDialog();

            if(msg != null)
            {
                if(msg.MsgType.Equals(MessageType.Error))
                {
                    //CloseWaitingDialog();
                    ShowError(ResourceLabel.Get(msg));
                }
                else
                {
                    //TODO: using transaction
                    UpdateUserGroup();

                    //CloseWaitingDialog();
                    ShowInfor(ResourceLabel.Get(msg));
                    ClearForm();
                    BindDataForGrid();
                    upnlGrid.Update();
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                // Do delete action
                DoAction(PageAction.Delete);
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void DoAction(PageAction action)
        {
            // Get list of groupId that to be update
            var strIds = Request["listIds"];

            if ((strIds == null) || (string.Empty.Equals(strIds)))
            {
                CloseWaitingDialog();
                return;
            }

            var objList = new List<Domain.UserAdmin>();
            var listIds = strIds.Split(',');

            foreach (var userAdminId in listIds)
            {
                var updateDate = CommonFunc.GetValueFromGrid(gvNguoiDung, "UserAdminId", userAdminId, "UpdateDate");
                var objInfo = new Domain.UserAdmin
                {
                    Id = int.Parse(userAdminId),
                    UpdateDate = DateTime.Parse(updateDate),
                    UpdateBy = LoginInfo.Username
                };

                // Add group to list
                objList.Add(objInfo);
            }

            // Delete group list
            var msg = _objDao.UpdateList(objList, action);

            // Show message
            if (msg.MsgType == MessageType.Error)
            {
                ShowInfor("Xóa không thành công.");
                CloseWaitingDialog();
            }
            else
            {

                ClearForm();
                ShowInfor("Xóa thành công.");
                BindDataForGrid();
                upnlGrid.Update();
                CloseWaitingDialog();
            }

            // Reload login info
            //AppCtrl.ReloadLoginInfo();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
            CloseWaitingDialog();
        }

        protected void gvNguoiDung_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditUser":
                        var user = _objDao.Get(null, Int32.Parse(id));

                        if (user != null)
                        {
                            UpdateMode = Mode.Update;
                            SetControlValue(hdId.ClientID, user.Id.ToString());
                            SetControlValue(txtUSERNAME.ClientID, user.Username);
                            SetControlValue(txtMaNv.ClientID, user.MaNV);
                            //SetControlValue(txtPASSWORD.ClientID, user.Password);

                            UserId = user.Id;

                            LoadGroupDataList();
                            //cbActive.Checked = user.Active;
                            
                            upnlCustomers.Update();
                            CloseWaitingDialog();
                        }
                        else
                        {
                            CloseWaitingDialog();
                            ShowInfor("Người dùng không tồn tại.");
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        #region Nhân viên
        protected void btnFilterNV_Click(object sender, EventArgs e)
        {
            BindNhanVien();
            CloseWaitingDialog();
        }

        private void BindNhanVien()
        {
            var list = _nvdao.Search(txtKeywordNV.Text.Trim(), null);
            gvNhanVien.DataSource = list;
            gvNhanVien.PagerInforText = list.Count.ToString();
            gvNhanVien.DataBind();

            CloseWaitingDialog();
        }

        protected void btnBrowseNhanVien_Click(object sender, EventArgs e)
        {
            BindNhanVien();
            upnlNhanVien.Update();
            UnblockDialog("divNhanVien");
        }

        protected void gvNhanVien_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var id = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "SelectMANV":
                        var nv = _nvdao.Get(id);
                        if (nv != null)
                        {
                            SetControlValue(txtUSERNAME.ClientID, nv.MaNV);
                            SetControlValue(txtMaNv.ClientID, nv.MaNV);
                            upnlCustomers.Update();

                            HideDialog("divNhanVien");
                            CloseWaitingDialog();

                            txtUSERNAME.Focus();
                        }

                        CloseWaitingDialog();

                        break;

                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        #endregion

        protected void dpDataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item &&
             e.Item.ItemType != ListItemType.AlternatingItem) return;

            var checkbox = e.Item.FindControl("chkGroupUser") as HtmlInputCheckBox;
            if (checkbox == null) return;

            var source = dpDataList.DataSource as List<Domain.Group>;
            if (source == null) return;

            var group = source[e.Item.ItemIndex];

            var grpusr = _objDao.GetGroupUser(group.Id, UserId.Value);

            checkbox.Checked = grpusr != null;
        }
    }
}